/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-04-20 16:04:42
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-07-25 15:56:38
 * @FilePath: \vite-project\src\hooks\quotation\useInquiry.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
    acceptPriceEvaluateSheet,
    addPriceEvaluateSheet,
    availableValuationEvaluateStandard,
    editPriceEvaluateSheet,
    getPriceEvaluateSheetById,
    refusePriceEvaluateSheet,
    stuffPriceEvaluateSheet,
} from '@/apis/recycleCar/quotation';
import { evaluateMaterialWorth } from '@/apis/recycleCar/purchase/materiel';
import AcceptForm from '@/components/recycleCar/quotation/AcceptForm';
import RefuseForm from '@/components/recycleCar/quotation/RefuseForm';
import { message, Modal } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom-v5-compat-dom';

export default function useInquiry() {
    const { id } = useParams();
    const [messageApi] = message.useMessage();
    const [current, setCurent] = useState<number>(0);
    const [basicFormData, setBasicFormData] = useState();
    const [priceFormData, setPriceFormData] = useState();
    const [initData, setInitData] = useState();
    const refuseRef = useRef<any>();
    const acceptRef = useRef<any>();
    const [result, setResult] = useState();
    const [nextLoading, setNextLoading] = useState(false);
    const [spining, setSpining] = useState(false);
    const [finishData, setFinishData] = useState();

    const back = () => {
        history?.back();
    };
    const onFinishBasicType02 = (formData: any, materialId?: any, refresh?: () => void) => {
        let isConditonCheck = true;
        formData?.conditions?.map((item) => {
            if (!item?.checked) {
                isConditonCheck = false;
            }
        });
        if (formData?.conditions?.length === 0 || !isConditonCheck) {
            setPriceFormData({
                ...formData,
            });
            setNextLoading(true);
            const fdata = formatFormData({
                ...(basicFormData || {}),
                ...(formData || {}),
            });
            fdata.materialId = materialId;
            evaluateMaterialWorth(fdata)
                .then((res) => {
                    setCurent(current + 2);
                    setResult(res);
                    refresh?.();
                })
                .finally(() => {
                    setNextLoading(false);
                });
        } else {
            setBasicFormData(formData);
            setCurent(current + 1);
        }
    };
    const onFinishBasic = async (formData: any) => {
        let isConditonCheck = true;
        formData?.conditions?.map((item) => {
            if (!item?.checked) {
                isConditonCheck = false;
            }
        });
        if (formData?.conditions?.length === 0 || !isConditonCheck) {
            const fdata = formatFormData({
                ...(formData || {}),
            });
            // 匹配不到质检规则、直接跳转完成
            if ((id && id !== 'add') || result?.id) {
                // 编辑
                editPriceEvaluateSheet({
                    id: result?.id ? result?.id : id,
                    ...fdata,
                })
                    .then((res) => {
                        setCurent(current + 2);
                        setResult(res);
                    })
                    .finally(() => {
                        setNextLoading(false);
                    });
            } else {
                // 新增
                addPriceEvaluateSheet(fdata)
                    .then((res) => {
                        setCurent(current + 2);
                        setResult(res);
                    })
                    .finally(() => {
                        setNextLoading(false);
                    });
            }
            setBasicFormData(formData);
        } else {
            setBasicFormData(formData);
            setCurent(current + 1);
        }
    };
    const onFinishPrice = async (formData: any, type?: string) => {
        setPriceFormData({
            ...formData,
        });
        setNextLoading(true);
        const fdata = formatFormData({
            ...(basicFormData || {}),
            ...(formData || {}),
        });
        const curId = id === 'add' ? '' : id || result?.id;
        if (type === 'draft') {
            // 草稿
            stuffPriceEvaluateSheet({
                ...(curId ? { id: curId } : {}),
                ...fdata,
            })
                .then((res) => {
                    // setCurent(current + 1);
                    setResult(res);
                    // 返回
                    back?.();
                })
                .finally(() => {
                    setNextLoading(false);
                });
        } else if (curId) {
            // 编辑
            editPriceEvaluateSheet({
                id: curId,
                ...fdata,
            })
                .then((res) => {
                    setCurent(current + 1);
                    setResult({
                        ...res,
                        id: curId,
                    });
                })
                .finally(() => {
                    setNextLoading(false);
                });
        } else {
            // 新增
            addPriceEvaluateSheet(fdata)
                .then((res) => {
                    setCurent(current + 1);
                    setResult(res);
                })
                .finally(() => {
                    setNextLoading(false);
                });
        }
    };
    const onFinishPriceCarStandard = async (formData: any, materialId?: any, refresh?: () => void) => {
        setPriceFormData({
            ...formData,
        });
        setNextLoading(true);
        const fdata = formatFormData({
            ...(basicFormData || {}),
            ...(formData || {}),
        });

        fdata.materialId = materialId;
        evaluateMaterialWorth(fdata)
            .then((res) => {
                setCurent(current + 1);
                setResult(res);
                refresh?.();
            })
            .finally(() => {
                setNextLoading(false);
            });
    };
    const onPre = (step?: number) => {
        switch (step) {
            case 2: {
                let isConditonCheck = true;
                priceFormData?.detailScore?.map((item) => {
                    if (!item?.value) {
                        isConditonCheck = false;
                    }
                });
                if (!priceFormData?.detailScore?.length || !isConditonCheck) {
                    // 无车辆价值评估‘
                    setCurent(current - 2);
                } else {
                    setCurent(current - 1);
                }
                break;
            }
            default: {
                setCurent(current - 1);
            }
        }
    };
    const formatFormData = (data) => {
        const fdata = {
            ...data,
            businessType: {
                id: data?.businessType?.value,
                name: data?.businessType?.label,
            },
            // source: {
            // 	value: data?.source?.value,
            // 	name: data?.source?.label,
            // },
            carCategory: {
                id: data?.carCategory?.value,
                name: data?.carCategory?.label,
            },
            weightUnit: {
                id: data?.weightUnit?.value,
                name: data?.weightUnit?.label,
            },
            modelMode: {
                id: data?.modelMode?.id,
                name: data?.modelMode?.id === 1 ? '车辆品牌' : '报废车类型',
            },
            model: {
                id: data?.model?.value,
                name: data?.model?.label,
            },
            conditions: initData?.conditions?.map((item, index) => ({
                ...item,
                checked: data?.conditions?.[index]?.checked,
            })),
            detailScore: data?.detailScore?.length
                ? initData?.scores?.map?.((item, index) => ({
                      ...item,
                      value: data?.detailScore?.[index]?.value,
                  }))
                : [],
        };
        return fdata;
    };

    const onFinish = (type?: string, form?: any, max?: number) => {
        switch (type) {
            case 'accept': {
                Modal.confirm({
                    width: 500,
                    title: '接受报价',
                    content: <AcceptForm maxPrice={max} ref={acceptRef} />,
                    okText: '确定',
                    cancelText: '取消',
                    centered: true,
                    onOk() {
                        return new Promise<void>(async (resolve, reject) => {
                            try {
                                acceptRef?.current
                                    ?.validateFields()
                                    .then((fdata) => {
                                        acceptPriceEvaluateSheet({
                                            id: result?.id ? result?.id : id,
                                            ...fdata,
                                            negotiatePrice: fdata?.negotiatePrice * 100,
                                        })
                                            .then(() => {
                                                setCurent(current + 1);
                                                messageApi.success('确定接受报价');
                                                resolve();
                                            })
                                            .catch(() => {
                                                reject();
                                            });
                                    })
                                    .catch((error) => {
                                        console.error(error);
                                        reject();
                                    });
                            } catch (error) {
                                reject();
                            }
                        });
                    },
                });
                break;
            }
            case 'reject': {
                Modal.confirm({
                    width: 500,
                    title: '拒绝报价',
                    content: <RefuseForm maxPrice={100} ref={refuseRef} />,
                    okText: '确定',
                    cancelText: '取消',
                    centered: true,
                    onOk() {
                        return new Promise<void>(async (resolve, reject) => {
                            try {
                                refuseRef?.current
                                    ?.validateFields()
                                    .then((fdata) => {
                                        refusePriceEvaluateSheet({
                                            id: result?.id ? result?.id : id,
                                            ...fdata,
                                        })
                                            .then(() => {
                                                back();
                                                messageApi.success('确定拒绝报价');
                                                resolve();
                                            })
                                            .catch(() => {
                                                reject();
                                            });
                                    })
                                    .catch(() => {
                                        reject();
                                    });
                            } catch (error) {
                                reject();
                            }
                        });
                    },
                });
                break;
            }
            case 'fallback': {
                back();
                break;
            }
        }
    };

    const clearData = () => {
        setCurent(0);
        setBasicFormData(void 0);
        setPriceFormData(void 0);
        setResult(void 0);
    };

    useEffect(() => {
        // 获取条件项
        availableValuationEvaluateStandard({}).then((res) => {
            setInitData(res);
        });
        if (id && id !== 'add') {
            setSpining(true);
            getPriceEvaluateSheetById({
                id,
            })
                .then((res) => {
                    setBasicFormData({
                        name: res?.name,
                        // source: {
                        // 	label: res?.source?.name,
                        // 	value: res?.source?.value,
                        // },
                        carCategory: {
                            label: res?.carCategory?.name,
                            value: res?.carCategory?.id,
                        },
                        businessType: {
                            label: res?.businessType?.name,
                            value: res?.businessType?.id,
                        },
                        conditions: res?.conditions,
                        weight: res?.weight,
                        weightUnit: {
                            label: res?.weightUnit?.name,
                            value: res?.weightUnit?.id,
                        },
                        modelMode: {
                            label: res?.modelMode?.name,
                            id: Number(res?.modelMode?.id),
                        },
                        model: {
                            label: res?.model?.name,
                            value: res?.model?.id,
                        },
                    });
                    setPriceFormData({
                        detailScore: res?.detailScore,
                    });
                    setFinishData({
                        refuseReason: res?.refuseReason,
                        result: res?.result,
                        score: res?.score,
                        status: res?.status,
                    });
                })
                .finally(() => {
                    setSpining(false);
                });
        }
    }, []);

    return {
        id,
        spining,
        nextLoading,
        initData,
        current,
        basicFormData,
        priceFormData,
        result,
        finishData,
        setCurent,
        onFinishBasic,
        onFinishBasicType02,
        onFinishPrice,
        onPre,
        onFinish,
        onFinishPriceCarStandard,
        clearData,
    };
}
